package com.sirc.zp.shiro;

import com.sirc.zp.domain.User;
import com.sirc.zp.service.PrivilegeService;
import com.sirc.zp.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 定制自己的MySQL realm类
 */
public class MySQLRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private PrivilegeService privilegeService;
    /**
     * 和授权相关的方法
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    /**
     * 和认证相关的设置
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;
        String username=usernamePasswordToken.getUsername();
        String password=new String(usernamePasswordToken.getPassword());
        User u=new User();
        u.setUsername(username);
        u.setPassword(password);
        User user = userService.findUser(u);
        if(user==null){
            //没找到帐号
            throw new UnknownAccountException();
        }else{
            SecurityUtils.getSubject().getSession().setAttribute("user", user);
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,getName());
            return authenticationInfo;
        }
    }
}
